package xj.graph2d.app.prop;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.Icon;

import xj.graph2d.DrawAttr;
import xj.graph2d.FontAttr;
import xj.graph2d.FontMap;

public class FontIcon implements Icon {

  protected Dimension dim;

  protected int fontSize = 16;

  protected String fontName = "SansSerif";

  protected int fontStyle = Font.BOLD;

  protected String string;

  protected static FontMap fontmap;

  static {
    fontmap = FontMap.getInstance();
  }

  public FontIcon(int width, int height, String string) {
    dim = new Dimension(width, height);
    this.string = string;
  }

  public FontIcon() {
    dim = new Dimension(24, 16);
    string = "Aa";
  }

  public String getFontName() {
    return fontName;
  }

  public void setFontName(String fontName) {
    this.fontName = fontName;
  }

  public int getFontStyle() {
    return fontStyle;
  }

  public void setFontStyle(int fontStyle) {
    this.fontStyle = fontStyle;
  }

  public int getFontSize() {
    return fontSize;
  }

  public void setFontSize(int fontSize) {
    this.fontSize = fontSize;
  }

  public void setFont(FontAttr fontAttr) {
    if (fontAttr != null) {
      this.fontName = fontAttr.fontName;
      this.fontStyle = fontAttr.fontStyle;
      this.fontSize = fontAttr.fontSize;
    }
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
	RenderingHints.VALUE_ANTIALIAS_ON);
    g2.clipRect(x, y, dim.width, dim.height);
    Color oldColor = g2.getColor();

    //
    // g2.setColor(Color.white);
    // g2.fillRect(x, y, getIconWidth(), getIconHeight());
    //

    //g2.setColor(Color.black);
    g2.setColor(DrawAttr.defaultPenColor);
    int fn = fontmap.findFont(fontName, fontStyle, fontSize);
    Font font = fontmap.getFont(fn);
    g2.setFont(font);
    FontMetrics fm = g2.getFontMetrics();
    int width = fm.stringWidth(string);
    g2.drawString(string, x + (dim.width - width) / 2, y + dim.height - 2
	- (dim.height - fontSize) / 2);
    g2.setColor(oldColor);
  }

  public int getIconWidth() {
    return dim.width;
  }

  public int getIconHeight() {
    return dim.height;
  }

}
